package icu.d4peng.basic.satoken.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.annotation.Order;

import cn.dev33.satoken.exception.RequestPathInvalidException;
import cn.dev33.satoken.strategy.SaStrategy;
import cn.dev33.satoken.util.SaTokenConsts;

/**
 * SaPathCheckFilterForServlet:路径过滤器
 *
 * @author d4peng <a href="d4peng@qq.com">d4peng@qq.com</a>
 * @since 2023.12.02
 */
@Order(SaTokenConsts.PATH_CHECK_FILTER_ORDER)
public class SaPathCheckFilterForServlet implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		// 校验本次请求 path 是否合法
		try {
			HttpServletRequest req = (HttpServletRequest) request;
			SaStrategy.instance.checkRequestPath.run(req.getRequestURI(), request, response);
		}
		catch (RequestPathInvalidException e) {
			if (SaStrategy.instance.requestPathInvalidHandle == null) {
				response.setContentType("text/plain; charset=utf-8");
				response.getWriter().print(e.getMessage());
				response.getWriter().flush();
			}
			else {
				SaStrategy.instance.requestPathInvalidHandle.run(e, request, response);
			}
			return;
		}

		// 向下执行
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) {
	}

	@Override
	public void destroy() {
	}

}
